package com.ijunfu.chatper03.ws;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *
 * @Title  : WebSocket 消息处理器
 * @Author : ijunfu <ijunfu@163.com>
 * @Date   : 2024/2/13 20:44
 * @Version: 1.0
 * @Motto  : 简洁的代码是智慧的结晶 卓越的编码是对复杂性的优雅征服
 *
 */
@Slf4j
@Component
//@EnableScheduling
public class WebSocketHandler extends TextWebSocketHandler {

    private static final ConcurrentHashMap<String, SessionBean> POOL = new ConcurrentHashMap<>();

    private static AtomicInteger idClientMaker = new AtomicInteger(0);

    private static StringBuffer MSG_BUFFER = new StringBuffer();

    // 建立连接
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);

        SessionBean sessionBean = new SessionBean(session, idClientMaker.getAndIncrement());
        POOL.put(session.getId(), sessionBean);

        log.info("{}: 已连接\t\t在线人数：{}", session.getId(), POOL.size());

        MSG_BUFFER.append( sessionBean.getIdClient() + " 已进入群聊<br />");

        sendMessage(POOL);

    }

    // 收到消息
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);

        log.info("{}: {}", session.getId(), message.getPayload());

        MSG_BUFFER.append( POOL.get(session.getId()).getIdClient() + ": " + message.getPayload() + "<br />");

        sendMessage(POOL);
    }


    // 传输异常
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        super.handleTransportError(session, exception);

        if(session.isOpen()) {
            session.close();
        }
        POOL.remove(session.getId());
    }

    // 连接关闭
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);

        POOL.remove(session.getId());
        log.info("{}: 已断开\t\t在线人数：{}", session.getId(), POOL.size());

        MSG_BUFFER.append( POOL.get(session.getId()).getIdClient() + ": 已退出群聊" + "<br />");

        sendMessage(POOL);
    }

    public void sendMessage(Map<String, SessionBean> sessionBeanMap) {
        for(SessionBean sessionBean : sessionBeanMap.values()) {
            try {
                sessionBean.getSession().sendMessage(new TextMessage(MSG_BUFFER.toString()));
            } catch (IOException e) {
                e.printStackTrace();
                log.info("{}", e);
            }
        }
    }

    // 每2秒发送心跳
    /*@Scheduled(fixedDelay = 2000)
    public void sendMsg() throws IOException {
        for(SessionBean sessionBean : POOL.values()) {
            sessionBean.getSession().sendMessage(new TextMessage("心跳"));
        }
    }*/
}
